package com.pe1n.yangtaopai.view.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.pe1n.yangtaopai.R;
import com.pe1n.yangtaopai.bean.LoginBean;
import com.pe1n.yangtaopai.bean.UpdataNameBean;
import com.pe1n.yangtaopai.helper.BitmapCircleTransformation;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

public class LogInActivity extends AppCompatActivity {
    private RelativeLayout mRelativeLayoutBack;//返回
    public static final int TAKE_PHOTO=1;
    private String name;
    public static final int SHOW_PICTURE=2;
    private RelativeLayout  mRelativeLayoutTouXiang;//头像
    private EditText mEditTextNiCheng;//昵称
    private TextView mTextView;//确定;
    private ImageView imageView;
    private String string;//昵称
    private File outImageViewout;
    private EditText mEditTextUserName;//用户
    private EditText mEditTextUserPass;//密码
    private SharedPreferences sharedPreferences;
     private Uri uri;
   private UpdataNameBean updataNameBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        sharedPreferences=getSharedPreferences("myshared",0);
        mEditTextUserName= (EditText)findViewById(R.id.activity_register_username1);
        mEditTextUserPass= (EditText) findViewById(R.id.activity_register_userpasswd);
        imageView= (ImageView) findViewById(R.id.activity_register_imageView);
        //判断文件是否存在.然后得到图片
        if(new File(Environment.getExternalStorageDirectory(),"my_image.jpg").exists()) {
            isTouXiang(new File(Environment.getExternalStorageDirectory(),"my_image.jpg"));
        }
        mRelativeLayoutBack= (RelativeLayout) findViewById(R.id.activity_register_back);
        mRelativeLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRelativeLayoutTouXiang= (RelativeLayout) findViewById(R.id.activity_register_upDatatouXiang);
        mRelativeLayoutTouXiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //建一个文件,接收我们的照片
                outImageViewout=new File(Environment.getExternalStorageDirectory(),"my_image.jpg");
                if( outImageViewout.exists()){
                    outImageViewout.delete();
                }
                try {
                    outImageViewout.createNewFile();

                } catch (IOException e) {
                    e.printStackTrace();
                }
                 uri= Uri.fromFile(outImageViewout);
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                PackageManager packageManager=getPackageManager();
                List activities= packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
                boolean IsIntenSafe=activities.size()>0;
                if(IsIntenSafe){
                    startActivityForResult(intent,TAKE_PHOTO);
                }

            }
        });
        mEditTextNiCheng=(EditText) findViewById(R.id.activity_register_niChengEditText);
        mTextView= (TextView) findViewById(R.id.activity_register_true);
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 updataNameBean=  new UpdataNameBean();
                 updataNameBean.setName(mEditTextNiCheng.getText().toString());
                 name=mEditTextUserName.getText().toString();
                 String passWord=mEditTextUserName.getText().toString();
                //LoginBean loginBean=new LoginBean();
                if(name.equals("")) {
                    Toast.makeText(LogInActivity.this,"您输入的账户不能为空!",Toast.LENGTH_LONG).show();

                }
              /* else {
                    BmobQuery<LoginBean> bmobQuery = new BmobQuery<LoginBean>();
                    bmobQuery.getObject(name, new QueryListener<LoginBean>() {
                        @Override
                        public void done(LoginBean loginBean, BmobException e) {
                            if (e == null) {
                                //.xml文件中的昵称,直接保存起来 到界面在拿回来
                                sharedPreferences.edit().putString("niCheng", mEditTextNiCheng.getText().toString()).commit();
                                updataNameBean.setPath(Environment.getExternalStorageDirectory() + File.separator + "my_image.jpg");
                                EventBus.getDefault().postSticky(updataNameBean);
                                String string= mEditTextUserName.getText().toString();
                                //.xml文件中的用户名
                                //用于他来找到他的购物车的购物
                                sharedPreferences.edit().putString("shareUserName", string).commit();
                                finish();
                            } else {
                                Toast.makeText(LogInActivity.this, "您输入账号密码有误!", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }*/
                else{
                    BmobQuery<LoginBean> query = new BmobQuery<LoginBean>();
                    query.addWhereEqualTo("name",name);
                    query.findObjects(new FindListener<LoginBean>() {
                        @Override
                        public void done(List<LoginBean> list, BmobException e) {
                            if(e==null){
                                //.xml文件中的昵称,直接保存起来 到界面在拿回来
                                sharedPreferences.edit().putString("niCheng", mEditTextNiCheng.getText().toString()).commit();
                                updataNameBean.setPath(Environment.getExternalStorageDirectory() + File.separator + "my_image.jpg");
                                EventBus.getDefault().postSticky(updataNameBean);
                                String string= mEditTextUserName.getText().toString();
                                //.xml文件中的用户名
                                //用于他来找到他的购物车的购物
                                sharedPreferences.edit().putString("shareUserName", string).commit();
                                finish();
                            }
                            else{
                                Toast.makeText(LogInActivity.this, "您输入账号密码有误!", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }


            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //回调
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO :
                if( resultCode==RESULT_OK){
                    Intent intent=new Intent("com.android.camera.action.CROP");
                    if(data!=null){
                        intent.setDataAndType(data.getData(),"image/*");
                    }
                    else{
                        intent.setDataAndType(uri,"image/*");
                    }
                    intent.putExtra("scale",true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                    startActivityForResult(intent,SHOW_PICTURE);
                }
                break;
            case SHOW_PICTURE:

                if( resultCode==RESULT_OK){
                   //try {
                        //Bitmap bitMap= BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                     //  imageView.setImageBitmap(bitMap);
                   // } catch (FileNotFoundException e) {
                   // e.printStackTrace();
                //}
                    isTouXiang(new File(Environment.getExternalStorageDirectory(),"my_image.jpg"));

                }
       break;
            default:
                break;
        }


    }
    @Override
    protected void onResume() {
        super.onResume();
        if(new File(Environment.getExternalStorageDirectory(),"my_image.jpg").exists()) {
        File file=new File(Environment.getExternalStorageDirectory(),"my_image.jpg") ;
            isTouXiang(file);
        }
    }

    private void isTouXiang(File file) {
        Glide.with(LogInActivity.this)
                .load(file)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .transform(new BitmapCircleTransformation(LogInActivity.this))
                .into(imageView);
    }
}
